<template>
  <a-row type="flex" style="flex-flow: inherit;">
    <a-col :flex="toggle ? '260px' : '30px'" style="margin-right: 12px;background-color: #fff;">
      <depart-tree :rootOpened="true" :multi="false" @ok="getTreeData" @toggleBool="toggleBool" />
    </a-col>
    <a-col flex="auto" style="width:0;">
      <a-card :bordered="false" style="margin-bottom: 10px">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
          <a-form-model layout="inline" ref="ruleForm" :model="queryParam">
            <z-form-item :datas="fieldArr" :form="queryParam" :submitAction="{ show: true, toggle: true, span: 6 }"
              @change="getChangeTime" @onSubmit="onQuery" @onReset="onResetForm" />
          </a-form-model>
        </div>
      </a-card>
      <a-card :bordered="false">
        <!-- 操作按钮区域 -->
        <div class="table-operator">
          <div>
            <a-button @click="handleExport">导出</a-button>
          </div>
        </div>
        <!-- 表格展示 -->
        <div class="table-page-content">
          <z-table ref="table" rowKey="id" :showAlert="false" :showSelection="true" :loading="loading"
            :columns="columns" :dataSource="pageData" @selectedRow="onSelectedRow" @change="onTableChange" />
        </div>
        <!--弹窗区域-->
        <handle-modal ref="handleModalRef" @ok="onQuery" />
        <special-population-modal :personId="personId" ref="specialPopulationModalRef" @ok="onQuery" />
      </a-card>
    </a-col>
  </a-row>
</template>

<script>
import * as personServiceApi from '@/api/sjsk/personService'
import departTree from '../../modules/departTree'
import handleModal from '../../modules/handleModal'
import specialPopulationModal from '../../checkManage/specialPopulation/modules/AddModal'
import { downLoadFileReader } from '@/utils/export-util/util'

export default {
  components: { departTree, handleModal, specialPopulationModal },
  data() {
    return {
      loading: false,
      toggle: true,
      selectKeys: [],
      queryParam: {},
      initialPassword: 'sjsk@123',
      personId: null,
      applyingLabels: [
        { text: '变更执行地申请中', value: 'a' },
        { text: '省内异地管控申请中', value: 'b' },
        { text: '省外异地管控申请中', value: 'c' },
        { text: '同城转介申请中', value: 'd' },
        { text: '撤销省内异地管控申请中', value: 'e' },
        { text: '撤销省外异地管控申请中', value: 'f' },
        { text: '风险等级评估申请中', value: 'g' },
        { text: '请假申请中', value: 'h' },
        { text: '中止申请中', value: 'i' },
        { text: '特殊人员申请中', value: 'j' },
        { text: '美沙酮入组申请中', value: 'k' },
        { text: '结案评估审批中', value: 'l' },
      ],
      fieldArr: [
        { label: '类型', prop: 'sjskType', tagType: 'dict-select', dictCode: 'sjsk_type', span: 6 },
        { label: '戒康人员姓名', prop: 'name', tagType: 'input', span: 6 },
        { label: '身份证号', prop: 'identityCard', tagType: 'input', span: 6 },
        {
          label: '标签筛选',
          prop: 'labelType',
          tagType: 'dict-select',
          dictOptions: [
            { text: '请选择', value: '' },
            { text: '特殊人员', value: '1' },
            { text: '异地管控人员', value: '2' },
          ],
          span: 6,
          toggle: false,
        },
        { label: '执行情况', prop: 'personStatus', tagType: 'dict-select', dictCode: 'person_status', span: 6, toggle: false },
        { label: '执行时间', prop: 'date', tagType: 'range-picker', format: 'YYYY-MM-DD', span: 6, toggle: false },
        { label: '专职人员', prop: 'belongManagerName', tagType: 'input', span: 6, toggle: false }
      ],
      columns: [
        {
          title: '在线状态',
          width: 70,
          align: 'center',
          dataIndex: 'isOnline',
          customRender: (text, record, index) => {
            return (
              <a-tooltip placement="topLeft" title={text === 1 ? '在线' : '不在线'}>
                <a-badge color={text === 1 ? 'green' : '#ccc'} />
              </a-tooltip>
            )
          }
        },
        {
          title: '姓名',
          dataIndex: 'realName',
          width: 80,
          align: 'center',
          customRender: (text, record, index) => {
            return (
              <span>
                <j-ellipsis value={text} length={6} />
                {record.applyingLabel ?
                  <a-tooltip placement="topLeft" title={this.$filterDictText(this.applyingLabels, record.applyingLabel)}>
                    <a-icon type="tags" style="color: #40a9ff;font-size: 16px;" />
                  </a-tooltip> : null}
              </span>
            )
          }
        },
        {
          title: '身份证号',
          dataIndex: 'identityCard',
          width: 110,
          align: 'left',
          customRender: text => {
            return <j-ellipsis value={text} length={20} />
          }
        },
        {
          title: '类型',
          dataIndex: 'sjskType',
          width: 80,
          align: 'center',
          customRender: (text, record, index) => {
            return (
              <span style="position: relative;">
                <a-tooltip
                  placement="topLeft"
                  title={record.isSpecial == 1 ? '特殊' : ''}
                  visible={record.isSpecial == 1 ? true : false}
                  get-popup-container={this.getPopupContainer}
                  overlayClassName="ts-tooltip"
                >
                  {this.$filterDictTextByCache('sjsk_type', text)}
                </a-tooltip>
              </span>
            )
          }
        },
        {
          title: '联系电话',
          dataIndex: 'phone',
          width: 95,
          align: 'center'
        },
        {
          title: '户籍地区',
          dataIndex: 'householdTown',
          width: 100,
          align: 'center',
          customRender: text => {
            return <j-ellipsis value={text} length={14} />
          }
        },
        {
          title: '上次登录时间',
          dataIndex: 'loginTime',
          width: 100,
          align: 'center',
          customRender: text => {
            return text ? text : '--'
          }
        },
        {
          title: '执行情况',
          dataIndex: 'personStatus',
          width: 80,
          align: 'center',
          customRender: text => {
            return <j-ellipsis value={this.$filterDictTextByCache('person_status', text)} length={14} />
          }
        },
        {
          title: '操作',
          width: 120,
          align: 'center',
          dataIndex: 'action',
          customRender: (text, record, index) => {
            return (
              <a-space size={6}>
                <a-button type="link" style={'padding:0'} onClick={event => this.handleModal('account-management', record)}>账号管理</a-button>
                <a-button type="link" style={'padding:0'} onClick={event => this.resetPassword(record)}>重置密码</a-button>
                <a-dropdown>
                  <a-menu slot="overlay">
                    <a-menu-item key="1" disabled={this.$options.filters.isDisabled('d', record.applyingLabel)} onClick={event => this.handleModal('intra-city-referral', record)}> 同城转介 </a-menu-item>
                    <a-menu-item key="2" disabled={this.$options.filters.isDisabled('a', record.applyingLabel)} onClick={event => this.handleModal('remove-assgin', record)}> 变更执行地 </a-menu-item>
                    <a-menu-item key="4" disabled={this.$options.filters.isDisabled('b', record.applyingLabel) || this.$options.filters.isDisabled('c', record.applyingLabel)} onClick={event => this.handleModal('apply-remote-control', record)}> 申请异地管控 </a-menu-item>
                    {record.personStatus != 2 ?
                      <a-menu-item key="5" onClick={event => this.handleModal('ask-for-leave', record)}> 请假 </a-menu-item>
                      : record.personStatus == 2 ?
                        <a-menu-item key="6" onClick={event => this.resumptionLeave('resumption-leave', record)}> 销假 </a-menu-item>
                        : null}
                    <a-menu-item key="7" disabled={this.$options.filters.isDisabled('j', record.applyingLabel)} onClick={event => this.handleModal('special-population', record)}> 申请特殊人员 </a-menu-item>
                    <a-menu-item key="8" disabled={this.$options.filters.isDisabled('i', record.applyingLabel)} onClick={event => this.handleModal('discontinue', record)}> 中止 </a-menu-item>
                    <a-menu-item key="9" disabled={record.isUnderTreatment == 2 ? false : true} onClick={event => this.handleModal('methadone-enrollment', record)}> 美沙酮入组 </a-menu-item>
                    {record.personStatus == 3 ? <a-menu-item key="10" disabled={this.$options.filters.isDisabled('i', record.applyingLabel)} onClick={event => this.handleModal('continueDiscontinue', record)}> 继续执行 </a-menu-item> : ""}
                  </a-menu>
                  <a-button type="link" style={'padding:0'} > 特殊操作 <a-icon type="down" /> </a-button>
                </a-dropdown>
              </a-space>
            )
          }
        }
      ],
      pageFilter: {
        pageNo: 1,
        pageSize: 10
      },
      pageData: {},
      componentKey: this.$route.query.key,
      jsonParam: this.$route.query.jsonParam
    }
  },
  watch: {
    // 组织机构树-联动筛选人员列表
    'queryParam.departmentId'(newVal, oldVal) {
      if (this.componentKey && this.jsonParam) { //重新申请,弹框
        console.log("departmentId")
        console.log(this.queryParam.departmentId)
        this.handleModal(this.componentKey, this.jsonParam, this.queryParam.departmentId)
      }
      this.onQuery()
    }
  },
  filters: {
    // 判断字符串中是否包含某个字符串
    isDisabled(value, str) {
      let bool = str && str.includes(value)
      return bool ? true : false
    }
  },
  created() {

  },
  mounted() {

  },
  methods: {
    onQuery() {
      this.pageFilter.pageNo = 1
      this.refreshTable()
    },
    onResetForm() {
      const queryParam = (({ departmentId }) => ({ departmentId }))(this.queryParam) //清空对象，只保留departmentId元素
      this.queryParam = queryParam
      this.pageFilter.pageNo = 1
      this.pageFilter.pageSize = 10
      this.refreshTable()
      // this.$refs.ruleForm.resetFields()
    },
    onSelectedRow(keys) {
      this.selectKeys = keys
    },
    onTableChange(pagination, pageFilter, sorter) {
      this.pageFilter = Object.assign({}, this.pageFilter, pagination)
      this.refreshTable()
    },
    refreshTable() {
      let { date, ...dataParam } = this.queryParam // 剔除date元素，dataParam最新的对象
      let queryParam = Object.assign({}, dataParam, this.pageFilter)
      this.loading = true
      personServiceApi
        .getPersonList(queryParam)
        .then(res => {
          this.loading = false
          if (res.success) {
            this.pageData = res.result ? res.result : {}
            this.$refs.table.onClearRowKeys()
          } else {
            this.$message.warn(res.message ? res.message : '请求失败！')
          }
        })
        .catch(e => {
          this.loading = false
          this.$message.warn('请求失败！')
        })
    },
    // 弹窗操作
    handleModal(key, record) {
      // console.log(record);
      // console.log(this.$filterDictText(this.applyingLabels, record.applyingLabel));
      if (key && key === 'special-population') {
        this.$refs.specialPopulationModalRef.show(record, 1)//传1是为了和重新提交区分开
        this.personId = record.id
      } else {
        this.$refs.handleModalRef.show(key, record, this.queryParam.departmentId)
      }
      // this.$refs.handleModalRef.type = type
      this.$refs.handleModalRef.disableSubmit = false
    },
    // 重置密码
    resetPassword(record) {
      let that = this
      let content = <div style="color:red;">初始密码为{this.initialPassword}</div>
      this.$confirm({
        title: `确定重置密码?`,
        content: h => content,
        onOk() {
          // that.getRequest(key, record)
          const parameter = { sjskPersonId: record.id, password: that.initialPassword }
          personServiceApi.resetPassword(parameter).then((res) => {
            if (res.success) {
              that.$message.success(res.message ? res.message : '操作成功')
              that.onQuery()
            } else {
              that.$message.warn(res.message ? res.message : '操作失败')
            }
          }).catch(e => {
            that.$message.warn("操作失败！")
          })
        },
        onCancel() {
          console.log('Cancel')
        },
        class: 'confirm',
      })
    },
    // 销假
    resumptionLeave(key, record) {
      this.$refs.handleModalRef.show(key, record)
    },
    // 导出
    handleExport(record) {
      let that = this
      let selectList = this.$refs.table.getSelectedRows()
      let idList1 = selectList.map(v => v.id).filter(obj => obj !== null && obj !== undefined && obj !== '')
      let idList2 = record && Object.keys(record).length > 0 && record.id ? [record.id] : []
      let params = Object.assign(
        {},
        {
          idList: selectList.length > 0 ? idList1 : idList2,
          querySjskPersonVO: this.queryParam
        }
      )
      this.$confirm({
        title: `是否确认导出？`,
        okText: '确定',
        onOk() {
          personServiceApi.sjskExport(params).then(async res => {
            const fileName = '社戒社康人员列表数据.xlsx'
            await downLoadFileReader(res, fileName)
            that.$refs.table.onClearRowKeys()
          })
        }
      })
    },
    // 选中组织架构树，赋值到人员列表搜索框
    getTreeData(datas, id) {
      console.log(datas, id)
      this.$set(this.queryParam, 'departmentId', id)
    },
    // 组织架构树展开收起
    toggleBool(bool) {
      this.toggle = bool
    },
    // 获取组件的时间， prop为对应的字段，date为选中的时间值
    getChangeTime(prop, date) {
      if (prop === 'date') {
        this.$set(this.queryParam, 'startDate', date[0])
        this.$set(this.queryParam, 'endDate', date[1])
      }
    },
    getPopupContainer(trigger) {
      return trigger.parentElement;
    }
  }
}
</script>
<style lang="less" scoped>
@import '~@assets/less/common.less';

:deep(.ant-badge) {
  .ant-badge-status-dot {
    width: 10px;
    height: 10px;
  }
}

:deep(.ts-tooltip) {
  top: -26px !important;
  z-index: 1 !important;

  .ant-tooltip-inner {
    background-color: #fef0ef;
    color: #f59a23;
    min-height: auto;
    padding-top: 0;
    padding-bottom: 0;
    border: 1px #f59a23 solid;
  }

  .ant-tooltip-arrow::before {
    background-color: #f59a23;
    border: 1px #f59a23 solid;
  }
}
</style>
